<template>
	<view>
		<view class="container">

			<uni-card :is-shadow="false" is-full>
				<text class="uni-h6" style="text-align: center;display: block;font-size: 15px;">{{user.company}}\n
					{{user.realName}}</text>
			</uni-card>


			<!-- 打卡信息 -->
			<uni-section title="打卡信息" type="line">
				<uni-list>
					<uni-list-item :show-extra-icon="true" :extra-icon="location" :title="address" :show-badge="true" />
				</uni-list>
				<uni-list>
					<uni-list-item style="margin-top: 10px;" :showExtraIcon="true" :extra-icon="location1"
						:title="newDay + '--'+ currentTime" :show-badge="true" />
				</uni-list>
			</uni-section>

			<!-- // 已打卡信息 -->
			<uni-section title="今日打卡信息" type="line" padding>
				<cc-defineStep colors="#0055ff" :stepData="list2"></cc-defineStep>
			</uni-section>


			<!-- // 按键 -->
			<view class="checkin-container" @tap="toCheckin">
				<view class="content">
					<view style="font-size: 22px;font-weight: 400;font-family: cursive;">打卡</view>
					<view style="font-size: 22px;font-weight: 400;font-family: cursive; color: red;">
						{{ currentTimeNoSecond }}
					</view>
				</view>
			</view>

			<!-- 个人信息 -->
			<view style="margin-top: 20px;">
				<button type="primary" @click="updateAddress">更新定位</button>
			</view>
			<view style="margin-top: 10px;">
				<button type="primary" @click="goto('/pages/mine/mine')">个人信息</button>
			</view>



		</view>

	</view>
</template>

<script>
	import utils from '@/utils/utils.js';

	var QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
	var amapFile = require('../../lib/amap-wx.130.js');
	var qqmapsdk;
	export default {
		data() {
			return {
				active: 0,
				list2: [],

				// 已打卡信息

				// 用户信息
				user: null,

				// 时间
				currentTime: '',
				currentTimeNoSecond: '',
				newDay: '',

				// 地点
				address: '',

				canCheckin: false, // 判断是否可以考勤
				canCheckinTip: "", // 无法打卡提示
				showCamera: true,
				showImage: false,
				status: '',

				brand: '',
				ranking_work: '',
				ranking_off: '',
			}
		},

		onLoad() {
			let that = this
			// 检测登录
			this.checkLogin().then(async (result) => {
				that.user = result.user
				uni.setStorageSync("userInfo", result)
				uni.showLoading({
					title: "加载中",
					icon: 'none',
					mask: true
				})

				await that.updateClock()
				await that.getDeviceInfo()
				await that.addressUpdate().then(async function(res) {
					// 判断当前时间是否可以考勤
					await that.checkValidCanCheckIn();
					uni.stopPullDownRefresh()
				}, async function(err) {
					uni.showToast({
						title: err,
						mask: true,
						duration: 2000
					})
					await that.checkValidCanCheckIn();
					uni.stopPullDownRefresh()
				})
			})
		},

		onShow() {

		},

		onPullDownRefresh: function() {
			let that = this
			let p = new Promise(async (resolve, reject) => {
				await that.updateClock()
				await that.getDeviceInfo()
				await that.addressUpdate().then(async function(res) {
					// 判断当前时间是否可以考勤
					await that.checkValidCanCheckIn();
				}, async function(err) {
					uni.showToast({
						title: err,
						mask: true,
						duration: 2000
					})
					await that.checkValidCanCheckIn();
				})
			})
			let a = p

		},

		methods: {

			goto: function(url) {
				uni.navigateTo({
					url: url
				})
			},

			// 或得手机信息
			getDeviceInfo: async function() {
				let that = this
				await wx.getSystemInfo({
					success: async function(res) {
						that.brand = res.brand;
						console.log(that.brand)
					},
					fail: function(err) {
						console.log(err)
					}
				})
			},

			//检测是否可打卡
			checkValidCanCheckIn: async function() {
				let that = this
				await that.ajax(that.url.validCanCheckIn, 'GET', null, function(resp) {
					utils.logging('查看是否可以考勤', resp);
					let data = resp.data.data;
					that.status = data.status;
					that.ranking_work = data.rankingWork;
					that.ranking_off = data.rankingOff;
					console.log(that.status)
					that.canCheckin = false;
					that.list2 = []
					if (data.status != '当前可以考勤' && data.status != '今日已上班打卡') {
						uni.showToast({
							title: data.status,
							mask: true
						})
						let dateObj = new Date(data.checkin.workTime);
						let dateObj1 = new Date(data.checkin.offTime);
						let worktime = dateObj.getHours().toString().padStart(2, '0') + ":" + dateObj
							.getMinutes().toString().padStart(2, '0');
						let offTime = dateObj1.getHours().toString().padStart(2, '0') + ":" + dateObj1
							.getMinutes().toString().padStart(2, '0');
						that.updateList("上班 正常", worktime, data.checkin.workAddr, 0)
						that.updateList("下班 正常", offTime, data.checkin.offAddr, 1)
						that.canCheckinTip = "data.status"
					} else {
						if (data.checkin.identification == 1) {
							const res = data.checkin
							let dateObj = new Date(res.workTime);
							let worktime = dateObj.getHours().toString().padStart(2, '0') + ":" + dateObj
								.getMinutes().toString().padStart(2, '0');
							that.updateList("上班 正常", worktime, res.workAddr, 1)
							if (new Date().getHours() - dateObj.getHours() >= data.duration) {
								that.canCheckin = true
							} else {
								that.canCheckinTip = "下班太快了"
							}
						} else {
							that.canCheckin = true
						}
					}
				});
				uni.hideLoading()
				uni.hideToast()
			},


			// 时间
			updateClock: async function() {
				const that = this; // 保存页面引用以便后续使用

				// 更新时间并在页面上显示
				function update() {
					const now = new Date();
					const hours = now.getHours().toString().padStart(2, '0');
					const minutes = now.getMinutes().toString().padStart(2, '0');
					const seconds = now.getSeconds().toString().padStart(2, '0');
					const year = now.getFullYear();
					const month = now.getMonth();
					const day = now.getDate();

					const timeString = `${hours}:${minutes}:${seconds}`;
					that.newDay = year + '-' + month + '-' + day
					that.currentTime = timeString
					that.currentTimeNoSecond = `${hours}:${minutes}`;
				}

				await update(); // 立即显示时间

				// 每秒更新一次时间
				setInterval(() => {
					update();
				}, 1000);
			},

			// 手动更新地址
			updateAddress: function() {
				uni.showToast({
					title: "更新中",
					icon: 'loading'
				})
				let that = this
				that.addressUpdate().then(function(res) {
					uni.hideToast()
					uni.showToast({
						title: "成功",
						icon: 'success',
						duration: 1000
					})
				}, function(err) {
					uni.hideToast()
					uni.showToast({
						title: err,
						icon: 'error',
						duration: 1000
					})
				})
			},

			// 地址
			addressUpdate: async function() {
				const that = this
				return new Promise(async (resolve, reject) => {
					await uni.getLocation({
						type: 'gcj02', // 返回可以用于uni.openLocation的坐标
						isHighAccuracy: true,
						altitude: true,
						success: async function(res) {
							console.log('Latitude: ' + res.latitude + ', Longitude: ' + res
								.longitude);
							// 可以将 res.longitude 和 res.latitude 用于地图展示等
							const myAmapFun = new amapFile.AMapWX({
								key: 'e72d98c1eb004028c9bef97abe5bbd82',
							});
							await myAmapFun.getRegeo({
								location: `${res.longitude},${res.latitude}`,
								success(data) {
									const geographicLocation = this.location;
									const address = data[0].regeocodeData
										.formatted_address;
									console.log('所在位置：', address)
									that.address = address;
									that.geographicLocation = geographicLocation;
									resolve(address)
								},
								fail() {
									console.log('逆地理编码失败');
									reject('逆地理编码失败')
								}
							})
						},
						fail: function(error) {
							console.error('Location acquisition failed: ' + JSON.stringify(
								error));
							reject("获取位置出错")
						}
					});
				})
			},

			// 更新打卡记录
			updateList: async function(name, time, address, isNow) {
				let that = this
				let index = that.list2.push({
					name: name,
					time: time,
					desc: address,
					type: 1,
					isNow: isNow
				})
			},

			// 签到具体方法
			toCheckin: async function() {
				const that = this;

				if (that.status == "今天已下班打卡") {
					uni.showToast({
						title: that.status,
						mask: true,
						duration: 1000
					})
					return
				}
				if (!that.canCheckin) {
					uni.showToast({
						title: that.canCheckinTip,
						mask: true,
						duration: 1000
					})
					return
				}
				if (that.address == '') {
					uni.showToast({
						title: "定位失败",
						mask: true,
						duration: 1000
					})
					return
				}
				// 屏蔽，防止多点
				uni.showLoading({
					title: "打卡中",
					mask: true
				})

				// 更新定位
				await that.addressUpdate().then(function(res) {
					console.log("开始打卡")
				}, function(err) {
					uni.hideLoading()
					uni.showToast({
						title: "err",
						mask: true,
						duration: 1000
					})
					return
				});

				let data = {}
				data.address = that.address
				data.brand = that.brand
				console.log(data)
				await that.ajax(that.url.checkinNoFace, 'POST', data, function(resp) {
					let result = resp.data
					console.log(result)
					if (resp.statusCode === 200) {
						switch (result.code) {
							case (500): {
								uni.showToast({
									title: result.message,
									icon: 'none',
									duration: 1000
								});
							};
							break;
							case (200): {
								that.canCheckin = false
								let res = result.data.identification
								if (res == 1) {
									uni.showToast({
										title: '上班打卡成功',
										mask: true
									});

								} else {
									uni.showToast({
										title: '下班打卡成功',
										mask: true
									});
								}
							};
							break;
						}
					} else {
						uni.showToast({
							title: "系统错误！",
							icon: 'error',
							duration: 1000
						});
					}
					that.checkValidCanCheckIn()
				})

			}





		},

	}
</script>

<style lang="scss">
	.example-body {
		padding: 10px;
		padding-top: 0;
	}

	.custom-image-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.text {
		font-size: 14px;
		color: #333;
	}

	.checkin-container {
		width: 250rpx;
		height: 250rpx;
		margin: auto;
		border-radius: 50%;
		border: 25rpx solid #3a75c5;
		margin-top: 10rpx;
		align-items: center;
		justify-content: center;

		.content {
			margin-top: 40rpx;
			align-items: center;
			justify-content: center;
			text-align: center;
		}

		view {
			margin-top: 5rpx;
		}
	}

	.content {
		margin-top: 40rpx;
		align-items: center;
		justify-content: center;
		text-align: center;
	}

	.shield {
		pointer-events: none;
	}

	.show {}
</style>